package com.c9.config;

import com.c9.dao.PermissionRepository;
import com.c9.entity.Permission;
import com.c9.entity.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    @Autowired
    PermissionRepository permissionRepository;
    CustomFilterInvocationSecurityMetadataSource(PermissionRepository permissionRepository){
        this.permissionRepository=permissionRepository;
    }
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String requestUrl=((FilterInvocation)object).getRequestUrl();
        AntPathMatcher antPathMatcher=new AntPathMatcher();
        List<Permission> permissions=permissionRepository.findAll();
        for(Permission permission:permissions){
            if(antPathMatcher.match(permission.getName(),requestUrl)){
                List<Role> roles=permission.getRoles();
                String [] rolestr=new String[roles.size()];
                for(int i=0;i<roles.size();i++){
                    rolestr[i]=roles.get(i).getRoleName();
                    System.out.println(rolestr[i]);
                }
                return SecurityConfig.createList(rolestr);
            }
        }
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
